<template>
  <div class="page-env-detail">
    <!-- 面包屑 -->
    <!-- <Breadcrumb>
      <BreadcrumbItem to="/home/environment"><i class="ivu-icon ivu-icon-home"></i> 环境中心</BreadcrumbItem>
      <BreadcrumbItem :title="'环境(' + (environment.environmentName ? environment.environmentName : environment.environmentId) + ')'">{{environment.environmentName ? environment.environmentName : environment.environmentId}}</BreadcrumbItem>
    </Breadcrumb> -->

    <div class="environment-info">
      <h4 class="zl-title">基本信息</h4>
      <Spin fix v-if="isLoading"></Spin>
      <div class="environment-info-box" v-else>
        <Row :gutter="10">
          <Col span="8" class="f-nowrap"><span class="info-title">环境名称：</span>{{environment.environmentName ? environment.environmentName : environment.environmentId}}</Col>
          <Col span="7" class="f-nowrap" v-if="environment.secondaryDomain"><span class="info-title">域名：{{environment.secondaryDomain}}{{domain | domainDot}}</span></Col>
          <Col span="9"><span class="info-title">创建时间：</span>{{environment.createTime}}</Col>
          <Col span="8"><span class="info-title">容器CPU最小值/最大值(mCpu)：</span>{{environmentInfo.containerDefaultRequestCpu}}/{{environmentInfo.containerDefaultCpu}}</Col>
          <Col span="16"><span class="info-title">容器内存最小值/最大值(Gi)：</span>{{environmentInfo.containerDefaultRequestMemory}}/{{environmentInfo.containerDefaultMemory}}</Col>
          <Col span="24"><span class="info-title">描述：</span>{{environmentInfo.description ? environmentInfo.description : '暂无描述'}}</Col>
        </Row>
      </div>
    </div>

    <!-- <monitor :environmentId="environmentId" title="环境运行情况"></monitor> -->

    <!-- 服务组列表（分组展示） -->
    <h4 class="zl-title">服务
      <div class="fr">
        <search placeholder="搜索服务/服务组" @change="searchService"></search>
        <Button type="primary" @click="serviceGroupMani" class="button-add"> <Icon type="md-add" /> <span class="button-name">添加服务组</span> </Button>
        <Button type="primary" @click="addModifyService()" class="button-add"> <Icon type="md-add" /> <span class="button-name">添加服务</span> </Button>
      </div>
    </h4>
    <div class="zl-page-loading" v-if="isLoading">
      <Spin class="zl-page-loading" fix></Spin>
    </div>
    <Card class="group-card" v-else>
      <div class="group-box-list" v-if="serviceGroupList.length > 0">
        <div class="group-box" v-for="group in serviceGroupList">
          <header class="group-head">
            <Row :gutter="8">
              <Col :span="6">
                <Icon type="md-list" />
                <div class="zl-link" @click="groupDetail(group)"> {{group.name}} </div>
              </Col>
              <Col :span="18">
                <div class="fr">
                  <div class="button-inner" @click="serviceGroupDelete(group)"><Icon type="md-trash" /> 删除</div>
                  <div class="button-inner" @click="serviceGroupMani(group)"><Icon type="ios-create-outline" /> 编辑</div>
                  <div class="button-inner" @click="addModifyService(group.id)" ><Icon type="md-add" /> 添加服务</div>
                </div>
              </Col>
            </Row>
          </header>
          <div class="group-body">
            <div class="service-box flex" v-for="service in group.serviceList" v-if="group.serviceList.length > 0">
              <div class="flex-status">
                <i class="zl-badge" :class="{'badge-error': service.status !== 'active'}"></i>
              </div>
              <div class="flex-name zl-link" @click="serviceDetail(group, service)">{{service.id}}</div>
              <div class="flex-1 f-nowrap">
                <Tooltip :content="service.image" placement="top">镜像：{{service.image}}</Tooltip>
              </div>
              <div class="flex-mani">
                <div class="button-inner" @click="serviceUpdate(group.id, service)"><Icon type="md-arrow-round-up" /> 升级</div>
                <div class="button-inner" @click="addModifyService(group.id, service)"><Icon type="ios-create-outline" /> 编辑</div>
                <div class="button-inner" @click="removeService(group.id, service)"><Icon type="md-trash" /> 删除</div>
                <div class="button-inner" @click="startService(group.id, service)"><Icon type="ios-play" />  启用</div>
                <div class="button-inner" @click="stopService(group.id, service)"><Icon type="ios-pause" /> 停止</div>
                <div class="button-inner" @click="ServiceReboot(group.id, service)"><Icon type="md-power" /> 重启</div>
              </div>
            </div>
            <div class="service-box" v-else>暂无服务</div>
          </div>
        </div>
      </div>
      <div class="no-data" v-else>暂无服务、服务组，请先添加！</div>
    </Card>

    <!-- 添加服务组 -->
    <service-group-add :visible.sync="groupVisible" :form="serviceGroupForm" @finish="serviceGroupAddFinish"></service-group-add>

    <!-- 新增、编辑服务 -->
    <service-add-modal :visible.sync="serviceAddVisible" :params="serviceParams" @finish="addModifyServiceFinish" @on-add-group="serviceGroupMani"></service-add-modal>

    <!-- 升级弹窗 -->
    <Modal v-model="updateVisible" title="镜像升级" :loading="true" @on-ok="imageUpdateConfirm" >
      <Form :label-width="80" class="image-update-modal">
        <FormItem label="镜像版本">
          <Select v-model="imageForm.imageVersion">
            <Option value="image.name" v-for="image in imageVersionList" :key="image.name">{{image.name}}</Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>

  </div>
</template>

<script>
  import Monitor from '@/components/monitor'
  import Search from '@/components/search'
  import ServiceGroupAdd from '@/components/add-service-group/add'
  import ServiceAddModal from '@/components/add-service/modal'
  import Fetch from '@/api/request'
  export default {
    name: 'EnvironmentDetail',
    components: {Monitor, Search, ServiceGroupAdd, ServiceAddModal},
    data() {
      return {
        environmentId: '',
        environment: {},
        isLoading: true,
        columns: [{
          title: '服务组名称',
          render: (h, params) => {
            let name = params.row.name ? params.row.name : params.row.environmentId
            return h('span', {
              class: 'zl-link',
              on: {
                click: () => {
                  this.serviceDetail(params.row)
                }
              }
            }, name)
          }
        }, {
          title: '服务数',
          key: 'serviceCount'
        }, {
          title: '容器数',
          key: 'containerCount'
        }, {
          title: '操作',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.serviceDetail(params.row)
                  }
                }
              }, '操作')
            ])
          }
        }],
        serviceGroupList: [],
        environmentInfo: [],
        domain: '',
        groupVisible: false,
        serviceGroupForm: {},
        serviceAddVisible: false,
        serviceParams: {},
        serviceGroupAddObj: {},
        updateVisible: false,
        imageForm: {
          imageVersion: '',
          groupId: '',
          serviceId: ''
        },
        imageVersionList: [],
        dockerHubs: []
      }
    },
    mounted() {
      this.environmentId = this.$route.params.environmentId
      this.domain = localStorage.getItem('domain')
      this.init()
    },
    filters: {
      domainDot(name) {
        if (name && name.length > 0 && name[0] !== '.') {
          return '.' + name
        } else {
          return name
        }
      }
    },
    methods: {
      // 服务组详情
      groupDetail(group) {
        localStorage.setItem('groupName', group.name)
        this.$router.push('/home/environment/' + this.environmentId + '/' + group.id)
      },
      // 确定升级镜像
      imageUpdateConfirm() {
        Fetch.patch({
          url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + this.imageForm.groupId + '/services/' + this.imageForm.serviceId,
          params: {
            environmentId: this.$route.params.environmentId,
            groupId: this.imageForm.groupId,
            serviceId: this.imageForm.serviceId,
            image: this.imageForm.image + ':' + this.imageForm.imageVersion,
            patchType: 'image'
          }.then((res) => {
            if (res && res.code === '0') {
              this.$Message.success({
                content: '镜像升级成功！',
                duration: this.DURATION
              })
            } else {
              this.$Message.warning({
                content: res.message,
                duration: this.DURATION
              })
            }
          }).catch((err) => {
            this.$Message.error(err.message)
          })
        })
      },
      // 升级镜像弹出弹窗
      serviceUpdate(groupId, service) {
        this.imageForm.serviceId = service.id
        this.imageForm.groupId = groupId
        this.imageForm.image = service.image.split(':')[0]
        Fetch.get({
          url: '/api/harbor/images/' + service.image.split(':')[0] + '/tags?environment=' + this.$route.params.environmentId
        }).then((res) => {
          if (res && res.code === '0') {
            this.imageVersionList = res.data
            this.updateVisible = true
          } else {
            this.$Message.warning({
              content: res.message,
              duration: this.DURATION
            })
          }
        }).catch((err) => {
          this.$Message.error(err.message)
        })
      },
      // 重启服务
      ServiceReboot(groupId, service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定重启' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.delete({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + groupId + '/services/' + service.id + '/reboot'
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '重启' + service.id + '服务成功！',
                  duration: this.DURATION
                })
                this.init()
              } else {
                this.$Message.warning({
                  content: res.message || '重启失败',
                  duration: this.DURATION
                })
              }
              this.$Modal.remove()
            }).catch((err) => {
              this.$Modal.remove()
              this.$Message.error(err.message)
            })
          }
        })
      },
      // 启用服务
      startService(groupId, service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定启用' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.post({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + groupId + '/services/' + service.id + '/start'
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '启用' + service.id + '服务成功！',
                  duration: this.DURATION
                })
                this.init()
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误' || '启用失败',
                  duration: this.DURATION
                })
              }
              this.$Modal.remove()
            }).catch((err) => {
              this.$Modal.remove()
              this.$Message.error(err.message)
            })
          }
        })
      },
      // 停止服务
      stopService(groupId, service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定停止' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.post({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + groupId + '/services/' + service.id + '/stop'
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '停止' + service.id + '服务成功！',
                  duration: this.DURATION
                })
                this.init()
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误',
                  duration: this.DURATION
                })
              }
              this.$Modal.remove()
            }).catch((err) => {
              this.$Modal.remove()
              this.$Message.error(err.message)
            })
          }
        })
      },
      // 删除服务
      removeService(groupId, service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定删除' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.delete({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + groupId + '/services/' + service.id
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '删除' + service.id + '服务成功！',
                  duration: this.DURATION
                })
                this.init()
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误',
                  duration: this.DURATION
                })
              }
              this.$Modal.remove()
            }).catch((err) => {
              this.$Modal.remove()
              this.$Message.error(err.message)
            })
          }
        })
      },
      // 添加服务完成
      addModifyServiceFinish() {
        this.init()
      },
      // 添加修改服务， 有service则为修改
      addModifyService(groupId, service) {
        if (!groupId) {
          this.serviceParams = {
            groupId: '',
            serviceGroupList: this.serviceGroupList
          }
        } else {
          if (!service) {
            this.serviceParams = {
              groupId
            }
          } else {
            this.serviceParams = {
              groupId,
              service: Object.assign({}, service)
            }
          }
        }
        this.serviceAddVisible = true
      },
      // 服务详情
      serviceDetail(group, service) {
        localStorage.setItem('groupName', group.name)
        this.$router.push('/home/environment/' + this.environmentId + '/' + group.id + '/' + service.id)
      },
      // 初始化页面
      init() {
        Fetch.get({
          url: '/api/environment/info',
          params: {environmentId: this.environmentId}
        }).then((res) => {
          if (res && res.code === '0') {
            this.environment = res.data
            if (res.data && res.data.groups) {
              this.serviceGroupList = res.data.groups
              // 在添加服务弹窗中新增服务组后，会返回一个服务组对象, 用于在新增服务弹窗中自动填写服务组名称
              if (this.serviceGroupAddObj.id) {
                this.serviceParams = {
                  groupId: '',
                  serviceGroupList: this.serviceGroupList,
                  serviceGroupAddObj: Object.assign({}, this.serviceGroupAddObj)
                }
                this.serviceGroupAddObj = {}
              } else {
                this.serviceParams = {
                  groupId: '',
                  serviceGroupList: this.serviceGroupList
                }
              }
            }
            if (res.environmentInfo && res.environmentInfo.code === '0') {
              this.environmentInfo = res.environmentInfo.data
            } else {
              this.$Message.warning(res.environmentInfo.message)
            }
          } else {
            this.$Message.error(res.message || '服务器内部错误' || '环境信息获取失败！')
          }
          this.isLoading = false
        }).catch((error) => {
          this.$Message.error(error.message)
          this.isLoading = false
        })
      },
      // 删除服务组
      serviceGroupDelete(group) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定删除' + group.name + '服务组？',
          loading: true,
          onOk: () => {
            Fetch.delete({
              url: '/api/environments/' + this.environmentId + '/groups/' + group.id
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '删除' + group.name + '服务组成功！',
                  duration: this.DURATION
                })
                this.init()
                this.$Modal.remove()
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误',
                  duration: this.DURATION
                })
              }
            }).catch((err) => {
              this.$Message.error({
                content: err.message,
                duration: this.DURATION
              })
            })
          }
        })
      },
      // 添加服务组完成
      serviceGroupAddFinish(ret) {
        this.serviceGroupAddObj = ret
        this.init()
      },
      // 添加，编辑服务组
      serviceGroupMani(group) {
        if (group) {
          this.serviceGroupForm = {
            environmentId: this.environmentId,
            groupId: group.id,
            name: group.name,
            description: group.description ? group.description : ''
          }
        } else {
          this.serviceGroupForm = {
            environmentId: this.environmentId,
            groupId: '',
            name: '',
            description: ''
          }
        }
        this.groupVisible = true
      },
      // search可以是服务也可以是服务组
      searchService(search) {
        let temp = []
        this.environment.groups.forEach((group) => {
          let name = group.name ? group.name : group.environmentId
          if (name.indexOf(search) !== -1) {
            temp.push(group)
          } else if (group.serviceList && group.serviceList.length > 0) {
            for (let i = 0; i < group.serviceList.length; i++) {
              const s = group.serviceList[i]
              if (s.id.indexOf(search) !== -1) {
                temp.push(group)
                break
              }
            }
          }
        })
        this.serviceGroupList = temp
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.environment-info {
  position: relative;
  min-height: 160px;
}
.environment-info-box {
  line-height: 32px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #eee;
}
.modal-add {
  position: relative;
  padding: 10px 20px 10px 0;
}
.button-add {
  .iconfont:hover {
    color: #fff;
  }
  + .button-add {
    margin-left: 10px;
  }
}
.service-group-table {
  margin-top: 20px;
  margin-bottom: 50px;
}
.group-card {
  margin-top: 20px;
  margin-bottom: 50px;
  padding: 10px 0 30px 0;
  .no-data {
    text-align: center;
    padding: 10px 30px 0 30px;
    color: #999;
  }
}
.group-box {
  .group-head {
    background-color: #f5f5f5;
    line-height: 40px;
    padding: 0 10px;
    border-bottom: 1px solid #eee;
    .zl-link {
      display: inline-block;
    }
  }
}
.service-box {
  line-height: 40px;
  padding-right: 10px;
  .flex-status {
    width: 40px;
    text-align: center;
  }
  .flex-name {
    width: 15%;
    word-wrap:normal;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-right: 10px;
  }
}
.image-update-modal {
  padding: 30px 50px 30px 20px;
}
</style>
